package com.punch.course.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punch.common.dto.course.ClassDTO;
import com.punch.common.dto.course.ClassSaveOrUpdateDTO;
import com.punch.common.exception.BusinessException;
import com.punch.common.exception.CommonExceptionEnum;
import com.punch.common.utils.BigDecimalUtil;
import com.punch.course.exception.CourseExceptionEnum;
import com.punch.course.mapper.CourseSchoolMapper;
import com.punch.course.model.CourseClassGoods;
import com.punch.course.model.CourseSchool;
import com.punch.course.model.CourseTemp;
import com.punch.course.model.Goods;
import com.punch.course.service.CourseClassGoodsService;
import com.punch.course.service.CourseSchoolService;
import com.punch.course.service.CourseTempService;
import com.punch.course.service.GoodsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 课程授课学校表 服务实现类
 * </p>
 *
 * @author wjj
 * @since 2020-12-01
 */
@Service
public class CourseSchoolServiceImpl extends ServiceImpl<CourseSchoolMapper, CourseSchool> implements CourseSchoolService {

    @Resource
    private CourseTempService courseTempService;

    @Resource
    private CourseClassGoodsService courseClassGoodsService;

    @Resource
    private GoodsService goodsService;

    /**
     * 保存学校授课课程
     *
     * @param classSaveOrUpdateDTO 课程信息
     * @param classId              班级id
     * @param userId               当前用户uid
     * @param username             用户姓名
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveCourseSchool(ClassSaveOrUpdateDTO classSaveOrUpdateDTO, Long classId, Long userId, String username) {
        Long courseId = classSaveOrUpdateDTO.getCourseId();
        CourseTemp courseTempEX = courseTempService.getById(courseId);
        Optional.ofNullable(courseTempEX).orElseThrow(() -> new BusinessException(CourseExceptionEnum.COURSE_DETAIL_FAIL_NULL));
        CourseSchool courseSchool = new CourseSchool();
        BeanUtil.copyProperties(courseTempEX, courseSchool);

        courseSchool.setClassId(classId);
        courseSchool.setCourseTempId(courseId);
        courseSchool.setCreateId(userId);
        courseSchool.setCreateName(username);
        //特殊处理适用年级与上课周期
        handlerGradeAndWeek(courseSchool, classSaveOrUpdateDTO.getCourseWeek(), classSaveOrUpdateDTO.getCourseGrade());
        //设置填写的课程信息
        courseSchool.setCourseHourCount(classSaveOrUpdateDTO.getCourseHourCount());
        courseSchool.setCourseHourPrice(BigDecimalUtil.getMoneyFee(classSaveOrUpdateDTO.getCourseHourPriceShow()));
        courseSchool.setBuyFlag(classSaveOrUpdateDTO.getBuyFlag());
        //mybatis-plus自动生成
        courseSchool.setId(null);
        courseSchool.setCreateTime(null);
        courseSchool.setUpdateTime(null);
        //如果包含教具
        if (classSaveOrUpdateDTO.getGoodsFlag() == 1) {
            if (classSaveOrUpdateDTO.getGoodsId() == null || classSaveOrUpdateDTO.getGoodsId() == 0L) {
                throw new BusinessException(CommonExceptionEnum.PARAMETER_LESS);
            }
            CourseClassGoods courseClassGoods = new CourseClassGoods();
            courseClassGoods.setClassId(classId);
            courseClassGoods.setGoodsId(classSaveOrUpdateDTO.getGoodsId());
            Goods goodsEX = goodsService.getById(classSaveOrUpdateDTO.getGoodsId());
            Optional.ofNullable(goodsEX).orElseThrow(() -> new BusinessException(CourseExceptionEnum.GOODS_NOT_EXIST));
            courseClassGoods.setGoodsCover(goodsEX.getGoodsCover());
            courseClassGoods.setGoodsName(goodsEX.getGoodsName());
            courseClassGoods.setGoodsTitle(goodsEX.getGoodsTitle());
            courseClassGoods.setGoodsPrice(goodsEX.getGoodsPrice());
            courseClassGoodsService.save(courseClassGoods);
            courseSchool.setGoodsFlag(1);
            courseSchool.setGoodsAmount(goodsEX.getGoodsPrice());
        }
        save(courseSchool);

        return courseSchool.getId();
    }


    /**
     * 修改学校授课课程
     *
     * @param classSaveOrUpdateDTO 课程信息
     * @param classId              班级id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUnReleaseCourseSchool(ClassSaveOrUpdateDTO classSaveOrUpdateDTO, Long classId) {
        QueryWrapper<CourseSchool> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CourseSchool::getClassId, classId);
        CourseSchool courseSchoolEX = getOne(queryWrapper);
        Optional.ofNullable(courseSchoolEX).orElseThrow(() -> new BusinessException(CourseExceptionEnum.COURSE_DETAIL_FAIL_NULL));
        CourseSchool courseSchool = new CourseSchool();
        //特殊处理适用年级与上课周期
        handlerGradeAndWeek(courseSchool, classSaveOrUpdateDTO.getCourseWeek(), classSaveOrUpdateDTO.getCourseGrade());
        //设置填写的课程信息
        courseSchool.setCourseHourCount(classSaveOrUpdateDTO.getCourseHourCount());
        courseSchool.setCourseHourPrice(BigDecimalUtil.getMoneyFee(classSaveOrUpdateDTO.getCourseHourPriceShow()));
        courseSchool.setBuyFlag(classSaveOrUpdateDTO.getBuyFlag());
        courseSchool.setId(courseSchoolEX.getId());
        updateById(courseSchool);

    }

    /**
     * 修改学校授课课程--发布状态
     *
     * @param classDTO 课程信息
     * @param classId  班级id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateReleaseCourseSchool(ClassDTO classDTO, Long classId) {
        QueryWrapper<CourseSchool> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CourseSchool::getClassId, classId);
        CourseSchool courseSchoolEX = getOne(queryWrapper);
        Optional.ofNullable(courseSchoolEX).orElseThrow(() -> new BusinessException(CourseExceptionEnum.COURSE_DETAIL_FAIL_NULL));
        CourseSchool courseSchool = new CourseSchool();
        //设置填写的课程信息
        courseSchool.setCourseHourCount(classDTO.getCourseHourCount());
        courseSchool.setCourseHourPrice(BigDecimalUtil.getMoneyFee(classDTO.getCourseHourPriceShow()));
        courseSchool.setBuyFlag(classDTO.getBuyFlag());
        //特殊处理适用年级与上课周期
        handlerGradeAndWeek(courseSchool, classDTO.getCourseWeek(), classDTO.getCourseGrade());
        courseSchool.setId(courseSchoolEX.getId());
        updateById(courseSchool);
    }


    /**
     * 特殊处理  适用年级与上课周期
     *
     * @param courseSchool    班级课程信息
     * @param courseWeekList  周期
     * @param courseGradeList 年纪
     */
    private void handlerGradeAndWeek(CourseSchool courseSchool, List<Integer> courseWeekList, List<Integer> courseGradeList) {
        //上课周期 courseWeek 单独处理
        if (CollUtil.isNotEmpty(courseWeekList)) {
            courseWeekList.sort(Comparator.naturalOrder());//排序下
            StringBuilder sb = new StringBuilder();
            courseWeekList.forEach(courseWeek -> sb.append(courseWeek).append(","));
            sb.deleteCharAt(sb.length() - 1);
            courseSchool.setCourseWeek(sb.toString());
        }
        //适用年级 courseGrade
        if (CollUtil.isNotEmpty(courseGradeList)) {
            courseGradeList.sort(Comparator.naturalOrder());//排序下
            StringBuilder sb = new StringBuilder();
            courseGradeList.forEach(courseGrade -> sb.append(courseGrade).append(","));
            sb.deleteCharAt(sb.length() - 1);
            courseSchool.setCourseGrade(sb.toString());
        }
    }


}
